<?php
namespace Wechat\Controller;

class WxCommonController extends CommonController {
    
    public function index() {
        $where['customer_id'] = $this->customer_id;
        $where['type'] = I('get.type');
        if(I('get.keywords')) $where['keyword'] = array('like','%'.I('get.keywords').'%');
        $dataPage = D('WxCommon')->getPager($where);
        $list = $dataPage['data'];

        //如果是多图文列表则遍历子图文
        if (I('type') == '2') {
            foreach ($list as $key => $value) {
                $list[$key]['subRow'] = M('WxCommonDetail')->where(array('common_id' => $value['id']))->select();
                $list[$key]['previewLink'] = urlencode(U('preview_list',array('id'=>$value['id'])));//预览链接
            }
        }

        $this->info['list'] = $list;
        $this->info['page'] = $dataPage['page'];
        $this->assign($this->info);
        $this->display();
    }

    //图片列表
    public function index_pic() {
        $where['customer_id'] = $this->customer_id;
        $where['type'] = '3';
        if(I('get.keywords')) $where['keyword'] = array('like','%'.I('get.keywords').'%');
        $dataPage = D('WxCommon')->getPager($where);

        $this->info['list'] = $dataPage['data'];
        $this->info['page'] = $dataPage['page'];
        $this->assign($this->info);
        $this->display();
    }

    public function add() {
        if (IS_POST) {
            $data = I('post.info');
            //关键词过滤
            $data['keyword'] = trim(str_replace("，", ",", $data['keyword']), ',');
            $data['customer_id'] = $this->customer_id;
            $keywordArr = explode(',', $data['keyword']);
            $WxKeyword = M('WxKeyword');
            foreach($keywordArr as $v){
                $keywordRes = $WxKeyword->where(array('keyword'=>$v,'customer_id'=>$this->customer_id))->find();
                if(empty($data['id']) && $keywordRes){
                    $this->error("关键词 ".$v." 已存在，请更换");
                }elseif($data['id']){
                    if($kEditRes = $WxKeyword->where(array('common_id'=>array('neq',$data['id']),'keyword'=>$v))->find())
                        $this->error("关键词 ".$v." 已存在，请更换");
                }
            }
            if(empty($data['keyword'])) $this->error("请输入关键词");
            
            $res = $data['id'] ? M('WxCommon')->save($data) : M('WxCommon')->add($data);
            if ($res === false) {
                $this->error('保存失败');
            } else {
                //保存关键词
                $common_id = $data['id'] ? $data['id'] : $res;
                $typeStr = $data['type'] == '1' ? 'text' : 'single';
                $this->saveKeywords($WxKeyword, $common_id, $data['keyword'], $typeStr);
                $this->success('保存成功');
            }
        } else {
            $item = array();
            if(I('id')) $item = D('WxCommon')->find(I('id'));
            $this->info['item'] = $item;
            $this->info['upPageUrl'] = $_SERVER['HTTP_REFERER'];

            $this->assign($this->info);
            $this->display(I('type')=='1' ? 'save_text' : 'save_article');
        }
    }

    //添加图片回复
    public function add_pic() {
        if (IS_POST) {
            $data = I('post.info');
            //关键词过滤
            $data['keyword'] = trim(str_replace("，", ",", $data['keyword']), ',');
            $data['customer_id'] = $this->customer_id;
            $keywordArr = explode(',', $data['keyword']);
            $WxKeyword = M('WxKeyword');
            foreach($keywordArr as $v){
                $keywordRes = $WxKeyword->where(array('keyword'=>$v,'customer_id'=>$this->customer_id))->find();
                if(empty($data['id']) && $keywordRes){
                    $this->error("关键词 ".$v." 已存在，请更换");
                }elseif($data['id']){
                    if($kEditRes = $WxKeyword->where(array('common_id'=>array('neq',$data['id']),'keyword'=>$v))->find())
                        $this->error("关键词 ".$v." 已存在，请更换");
                }
            }
            if(empty($data['keyword'])) $this->error("请输入关键词");
            
            $res = $data['id'] ? M('WxCommon')->save($data) : M('WxCommon')->add($data);
            if ($res === false) {
                $this->error('保存失败');
            } else {
                //保存关键词
                $common_id = $data['id'] ? $data['id'] : $res;
                $typeStr = 'pic';
                $this->saveKeywords($WxKeyword, $common_id, $data['keyword'], $typeStr);
                $this->success('保存成功');
            }
        } else {
            $item = array();
            if(I('id')) $item = D('WxCommon')->find(I('id'));
            $this->info['item'] = $item;
            $this->info['upPageUrl'] = $_SERVER['HTTP_REFERER'];

            $this->assign($this->info);
            $this->display();
        }
    }
    
    //保存关键词
    private function saveKeywords($model, $common_id, $keyword, $type = 'text'){
        $model->where(array('common_id'=>$common_id, 'type'=>$type))->delete();
        $wordArr = explode(',', $keyword);
        foreach($wordArr as $word){
            $model->add(array('customer_id'=>$this->customer_id, 'common_id'=>$common_id, 'keyword'=>trim($word), 'type'=>$type));
        }
    }

    //添加子图文
    public function sub() {
        if (IS_POST) {
            $data = I('post.info');
            
            $res = $data['id'] ? M('WxCommonDetail')->save($data) : M('WxCommonDetail')->add($data);
            if ($res === false) {
                $this->error('保存失败');
            } else {
                $this->success('保存成功');
            }
        } else {
            $item = array();
            if(I('id')) $item = D('WxCommonDetail')->find(I('id'));
            $this->info['item'] = $item;
            $this->info['upPageUrl'] = $_SERVER['HTTP_REFERER'];

            $this->assign($this->info);
            $this->display('save_sub');
        }
    }

    public function del($id){
        $id = (int)$id;
        if($res = M('WxCommon')->delete($id)){
            M('WxKeyword')->where(array('common_id'=>$id))->delete();
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    //删除子图文
    public function del_sub($id){
        $id = (int)$id;
        if($res = M('WxCommonDetail')->delete($id)){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    /**
     * url-token
     */
    public function url_token(){
        // $this->info['url'] = 'http://'.$_SERVER['HTTP_HOST'].newU('api/'.$this->customer_id);
        $this->info['url'] = U('Api/index', array('id' => $this->customer_id), false, true);
        $this->info['token'] = $this->customer['username'];
        $this->assign($this->info);
        $this->display();
    }

    /**
     * 预览
     */
    public function preview_list($id){
        $list     = array();
        $WxCommon = M('WxCommon');

        //获取所有图文
        $list[] = $WxCommon->where(array('id'=>$id))->find();
        if ($commonDetail = M('WxCommonDetail')->where(array('common_id'=>$id))->select()) {
            foreach ($commonDetail as $dv) {
                $list[] = $dv;
            }
        }
        $this->assign('list',$list);
        $this->display();
    }
    
}
